package com.sali.Tree;

import java.util.ArrayList;
import java.util.List;

/**
 二叉树的下一个结点
 */
public class JZ_8 {

    List<TreeLinkNode> myList = new ArrayList<>();

    public TreeLinkNode GetNext(TreeLinkNode pNode) {
        if ( pNode == null ) {
            return null;
        }
        TreeLinkNode rootNode = pNode;
        while ( rootNode.next != null ) {
            rootNode = rootNode.next;
        }
        getRes(rootNode);

        for ( int i = 0; i < myList.size() - 1; i++ ) {
            if ( pNode == myList.get(i) ) {
                return myList.get(i+1);
            }
        }

        return null;
    }

    private void getRes(TreeLinkNode node) {
        if ( node == null ) {
            return;
        }
        getRes(node.left);
        myList.add(node);
        getRes(node.right);
    }

}

class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}